package com.cskaoyan.wx.service;

import com.cskaoyan.bean.reverseengineering.MarketStorage;
import com.cskaoyan.config.AliyunComponent;
import com.cskaoyan.mapper.MarketStorageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @author Charadic
 * @since 2022/05/07 15:43
 */
@Service
public class WxStorageServiceImpl implements WxStorageService {

    @Value("${spring.resources.static-locations}")
    private String domain;

    @Autowired
    MarketStorageMapper marketStorageMapper;

    @Autowired
    AliyunComponent aliyunComponent;

    @Override
    public MarketStorage upload(MultipartFile file, HttpServletRequest request) {
        MarketStorage marketStorage = new MarketStorage();

        // 文件名
        marketStorage.setName(file.getOriginalFilename());

        // 文件key --->  随机生成UID
        String uuid = UUID.randomUUID().toString();
        // 得到后缀 .jpg
        int index = file.getOriginalFilename().indexOf(".");
        String suffix = file.getOriginalFilename().substring(index);
        marketStorage.setKey(uuid + suffix);

        // 文件大小
        marketStorage.setSize((int) file.getSize());

        // type
        marketStorage.setType(file.getContentType());

        // // url
        // StringBuffer requestURL = request.getRequestURL();
        // int index1 = requestURL.indexOf("/wx");
        // String url = requestURL.substring(0, index1);
        // marketStorage.setUrl(url + "/wx/storage/fetch/" + uuid + suffix);

        // // 存储文件
        // try {
        //     int index2 = domain.indexOf(":");
        //     String substring1 = domain.substring(index2 + 1);
        //     file.transferTo(new File(substring1,
        //             uuid + suffix));
        // } catch (IOException e) {
        //     e.printStackTrace();
        // }
        String fileName = uuid + suffix;
        System.out.println(fileName);
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        aliyunComponent.fileUpload(fileName,inputStream);

        // url
        marketStorage.setKey(uuid + suffix);
        marketStorage.setUrl("https://" + aliyunComponent.getOss().getBucket() + "." + aliyunComponent.getOss().getEndPoint() + "/" + uuid + suffix);
        // addTime 和 updateTime
        Date date = new Date();
        marketStorage.setAddTime(date);
        marketStorage.setUpdateTime(date);


        marketStorageMapper.insert(marketStorage);


        return marketStorage;
    }
}
